#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/wait.h>

void child(char *args[], int n) {
    int fd;
    char c1 = args[n - 2][0], c2 = args[n - 2][1];
    char buf[256];

    if(c1 == '>' || c1 == '<') {
        strcpy(buf, args[n - 2]);
        args[n - 2] = NULL;
        if(c2 == '>') strcpy(buf, buf + 2);
        else strcpy(buf, buf + 1);

        if(c2 == '>') {
            fd = open(buf, O_RDWR | O_CREAT | O_APPEND, 0777);
            dup2(fd, 1);     
        } else if(c1 == '<') {
            fd = open(buf, O_RDWR, 0777);
            dup2(fd, 0);
        } else {
            fd = open(buf, O_RDWR | O_CREAT | O_TRUNC, 0777);
            dup2(fd, 1);
        }

        close(fd);
    }
    execvp(args[0], args);
}

int main() {
    while(1) {
        printf("ysq> ");

        char line[1024];
        fgets(line, 1024, stdin);
        char *p = strchr(line, '\n');  // fgets会读入换行，需要把line末尾的换行改为'\0'
        *p = '\0';

        int n = 0;
        char *args[64];
        char *delim = " ";
        args[n ++] = strtok(line, delim);
        while((p = strtok(NULL, delim)))
            args[n ++] = p;
        args[n ++] = NULL;
        
        // 父进程内置命名处理
        if(!strcmp(args[0], "exit")) {
            exit(0);
        } else if(!strcmp(args[0], "pwd")) {
            char buf[1024];
            getcwd(buf, 1024);
            printf("%s\n", buf);
        } else if(!strcmp(args[0], "cd")) {
            char buf[1024];
            getcwd(buf, 1024);
            strcat(buf, "\\");
            strcat(buf, args[1]);
            chdir(buf);
        } else {  // 子进程处理
            pid_t pid = fork();
            if(pid == 0) {
                child(args, n);
                
            }
            wait(NULL);
        }
    }
    return 0;
}
